#!/usr/bin/python


"""
Binary tree algorith

1. Generate a Btree using given integer values
2. Parse the tree
3. Search for a particular node (number)
4. Auto insertion of new numbers
"""


class Node(object):
    """
    This class impelments the behaviour of an individual node. in the tree
    """
    
        
    def __init__(self, value=None):
        self.__v__ = value
        self.__ln__ = None
        self.__rn__ = None
    
    
    def getLeftNode(self):
        """
        Get left Node of the node
        """
        return self.__ln__
    
    def setLeftNode(self, ln):
        """
        Set value for left node
        """
        self.__ln__ = ln
    
    def getRightNode(self):
        """
        Get right node of the node
        """
        return self.__rn__
    
    def setRightNode(self, rn):
        """
        Set value for right node
        """
        self.__rn__ = rn
    
    def getValue(self):
        """
        Get value assigned to the node.
        """
        return self.__v__
    
    def setValue(self, v):
        """
        Get value assigned to the node.
        """
        self.__v__ = v
    
    def __str__(self):
        """
        print friendly representation of each node
        """
        return "<Node value=%s, ln=%s, rn=%s>"%(self.getValue(), self.getLeftNode(), 
                                                self.getRightNode())

class BTree(object):
    """
    Class for BTree
    """
    
    def __init__(self, root=Node(None)):
        self.__root__ = root
        
        
    def getRoot(self):
        """
        Return root node.
        """
        return self.__root__
    
    def add(self, value):
        """
        Start with root.
        """
        r = self.getRoot()
        if r.getValue() == None:
            r.setValue(value)
            
        while True:
            v = r.getValue()
            if value == v:
                break
            if value < v:
                if not r.getRightNode():
                    r.setRightNode(Node(value))
                else:
                    r = r.getRightNode()
            if value > v:
                if not r.getLeftNode():
                    r.setLeftNode(Node(value))
                else:
                    r = r.getLeftNode()

            
    def print_tree(self):
        print self.getRoot()
        
        
if __name__ == '__main__':
    t = BTree(Node(50))
    t.add(13)
    t.add(12)
    t.add(69)
    t.add(15)
    t.add(51)
    t.add(69)
    t.print_tree()
    